<template>
  <div class="role-detail-page">
    <!-- 按钮 -->
    <div class="role-detail-page-btn">
      <!-- <el-button type="plain-third" @click="handleBack" v-if="type == '1'"
        >返回</el-button
      > -->
      <el-button type="primary" @click="handleSave" v-if="type != '3'">{{ $t('common.base.save') }}</el-button>
      <el-button type="primary" @click="handleEdit" v-if="type == '3'">{{ $t('common.base.edit') }}</el-button>
    </div>
    <!-- 搜索项 -->
    <div class="role-detail-page-form">
      <el-form
        label-position="top"
        :model="form"
        :rules="rules"
        ref="form"
        
        :inline="true"
      >
        <el-form-item :label="$t('common.label.roleName')" prop="roleName">
          <span v-if="type == '3'">{{ form.roleName }}</span>
          <el-input
            v-else
            v-model="form.roleName"
            :placeholder="$t('common.placeholder.inputRoleName')"
            :style="{ width: '240px' }"
            :disabled="type == '2'"
          ></el-input>
        </el-form-item>

        <el-form-item :label="$t('common.label.describe')">
          <span v-if="type == '3'">{{ form.describe }}</span>
          <el-input
            v-else
            v-model="form.describe"
            :placeholder="$t('common.placeholder.languageSetTextarea')"
            :style="{ width: '480px' }"
            type="textarea"
            resize="none"
            autosize
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 展开 or 收起 -->
    <div class="role-detail-page-extension" @click="handleClickBtn">
      <span v-if="!isExpand">{{ $t('common.base.expandAll') }}<i class="el-icon-arrow-down"></i></span>
      <span v-else>{{ $t('common.base.collapseAll') }}<i class="el-icon-arrow-up"></i></span>
    </div>

    <!-- 表格 -->
    <div class="role-detail-page-table">
      <el-table
        ref="table"
        :data="tableData"
        row-key="id"
        border
        default-expand-all
        header-row-class-name="common-list-table-header taks-list-table-header"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column align="center" width="50" v-if="type != '3'">
          <template slot="header" slot-scope="scope">
            <el-checkbox
              v-model="checkedAll"
              :indeterminate="isAllIndeterminate"
              @change="handleCheckAll"
            />
          </template>
        </el-table-column>
        <!-- 应用 -->
        <el-table-column :label="$t('common.label.appPermission')" width="180">
          <template slot-scope="scope">
            <div
              v-if="scope.row.authType == 'module'"
              :style="{ display: 'inline-block' }"
            >
              <el-checkbox
                v-model="scope.row.checked"
                :indeterminate="scope.row.isIndeterminate"
                :label="scope.row.groupName"
                v-if="type != '3'"
                @change="
                  checked => {
                    handleCheckModule(checked, scope.row);
                  }
                "
              >
              </el-checkbox>
              <span v-else>{{ scope.row.groupName }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 模块 -->
        <el-table-column :label="$t('common.label.modulePermission')" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.authType == 'page'">
              <el-checkbox
                v-model="scope.row.checked"
                :indeterminate="scope.row.isIndeterminate"
                v-if="type != '3'"
                @change="
                  checked => {
                    handleCheckPage(checked, scope.row);
                  }
                "
              >{{ scope.row.module }}</el-checkbox
              >
              <span v-else> {{ scope.row.module }} </span>
            </div>
          </template>
        </el-table-column>
        <!-- 功能 -->
        <el-table-column :label="$t('common.label.functionPermission')">
          <template slot-scope="scope">
            <div>
              <el-checkbox-group
                v-model="scope.row.checkedStatus"
                v-if="type != '3'"
                @change="
                  checked => {
                    handleCheckedFunc(checked, scope.row);
                  }
                "
              >
                <el-checkbox
                  v-for="item in scope.row.functionList"
                  :key="item.id"
                  :label="item.id"
                >{{ item.btnName }}</el-checkbox
                >
              </el-checkbox-group>
              <div v-else>
                <span
                  v-for="item in scope.row.functionList"
                  :key="item.id"
                  :style="{ marginRight: '18px' }"
                >{{ item.btnName }}</span
                >
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- 数据权限 -->
        <el-table-column :label="$t('common.label.dataPermission')">
          <template slot-scope="scope">
            <div>
              <!-- <span>可查看数据范围</span> -->
              <el-radio-group v-model="scope.row.radio" v-if="type != '3'">
                <span v-for="item in scope.row.radioList" :key="item.id">
                  <el-radio :label="item.id">{{ item.name }}</el-radio>
                  <el-tooltip
                    placement="top"
                    v-if="item.name === $t('common.base.department')"
                    :style="{ marginRight: '14px' }"
                  >
                    <div slot="content">{{ $t('common.label.departmentInfo') }}</div>
                    <i class="iconfont icon-fd-info"></i>
                  </el-tooltip>
                </span>
              </el-radio-group>
              <div v-else>
                <span v-for="item in scope.row.radioList" :key="item.id">
                  {{ item.name }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import * as UserCenterApi from 'src/api/UserCenterApi.js';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { t } from '@src/locales'

export default {
  name: 'role-detail-view',
  data() {
    return {
      type: '', // 判断是新增、编辑、详情
      isExpand: true,
      form: {
        roleName: '',
        describe: '',
      },
      rules: {
        roleName: [
          { required: true, message: t('common.placeholder.inputRoleName'), trigger: 'change' },
        ],
      },
      checkedAll: true,
      isAllIndeterminate: false,
      tableData: [
        {
          id: 1,
          groupName: t('common.map.serviceDesk'),
          authType: 'module',
          checked: false,
          isIndeterminate: false,
          children: [
            {
              id: 11,
              pIndex: 0,
              module: t('common.base.serviceEvent'),
              authType: 'page',
              checked: false,
              checkedStatus: [],
              isIndeterminate: false,
              functionList: [
                {
                  id: '1',
                  btnName: t('common.base.view'),
                },
                {
                  id: '2',
                  btnName: t('common.base.detail'),
                },
                {
                  id: '3',
                  btnName: t('common.base.create'),
                },
                {
                  id: '4',
                  btnName: t('common.base.edit'),
                },
              ],
              radio: '1',
              radioList: [
                {
                  id: 0,
                  name: t('common.auth.personalPermission'),
                },
                {
                  id: 1,
                  name: t('common.auth.departmentPermission'),
                },
                {
                  id: '3',
                  name: t('common.auth.allPermission'),
                },
              ],
            },
          ],
        },
        {
          id: 2,
          groupName: t('common.base.taskCenter'),
          authType: 'module',
          checked: true,
          isIndeterminate: false,
          children: [
            {
              id: 21,
              pIndex: 1,
              module: t('common.base.taskManage'),
              authType: 'page',
              checked: false,
              checkedStatus: ['1', '2'],
              functionList: [
                {
                  id: '1',
                  btnName: t('common.base.view'),
                },
                {
                  id: '2',
                  btnName: t('common.base.detail'),
                },
                {
                  id: '3',
                  btnName: t('common.base.create'),
                },
                {
                  id: '4',
                  btnName: t('common.base.edit'),
                },
              ],
            },
          ],
        },
      ],
    };
  },
  created() {
    let pathname = window.location.pathname;
    if (pathname.includes('/security/role/create')) {
      this.type = '1';
    } else if (pathname.includes('/security/role/edit')) {
      this.type = '2';
    } else if (pathname.includes('/security/role/view/')) {
      this.type = '3';
    }
    this.getRoleAuthority();
    this.initData();
  },
  methods: {
    async getRoleAuthority(){
      try {
        let roleId = 3
        const { status, message, data } = await UserCenterApi.getRoleAuthority({roleId})
        if(status != 0) this.$platform.alert(message)
        const { authorities, dataTypes, sparepart2 } = data
        authorities.forEach(item=>{
          const data = {}
          data.id = item.groupId
          data.groupName = item.groupName
          data.authType = 'module'
          data.checked = false
          data.isIndeterminate = false


        })
        console.log(authorities, dataTypes, sparepart2);
      } catch (error) {
        console.error(error)
      }
    },
    // 点击展开收起功能按钮
    handleClickBtn() {
      this.isExpand = !this.isExpand;
      this.tableData.forEach(item => {
        this.$refs.table.toggleRowExpansion(item, this.isExpand);
      });
    },
    // // 点击返回按钮
    // handleBack() {
    //   // TODO
    //   parent.frameHistoryBack(window);
    // },
    // 点击保存按钮
    handleSave() {
      if (this.form.roleName.length == '0' || this.form.roleName == '') {
        return this.$message({
          message: t('common.placeholder.inputRoleName'),
          type: 'warning',
        });
      }
    },
    // 点击编辑按钮
    handleEdit() {
      let fromId = window.frameElement.getAttribute('id');
      // 1 暂时写死
      // this.$platform.openTab({
      //   id: `edit_role_${1}`,
      //   title: '编辑角色',
      //   close: true,
      //   url: `/security/role/edit/${1}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEditRole,
        key: '1',
        fromId
      })
    },
    // 默认初始状态
    initData() {
      let pNum = 0;
      let pColorNum = 0;
      this.tableData.forEach(item => {
        let countNum = 0; // 选中几个
        let colorNum = 0; // 子元素有几个-

        item.children.forEach(val => {
          if (val.checkedStatus.length == val.functionList.length) {
            val.isIndeterminate = false;
            val.checked = true;
            countNum++;
          } else if (val.checkedStatus.length == 0) {
            val.isIndeterminate = false;
            val.checked = false;
          } else {
            // 任意一个选中 - 标识
            val.isIndeterminate = true;
            val.checked = false;
            colorNum++;
          }
        });

        if (countNum == item.children.length) {
          item.isIndeterminate = false;
          item.checked = true;
          pNum++;
        } else if (countNum > 0 || colorNum > 0) {
          item.isIndeterminate = true;
          item.checked = false;
          pColorNum++;
        } else {
          item.isIndeterminate = false;
          item.checked = false;
        }
      });

      if (pNum == this.tableData.length) {
        this.checkedAll = true;
        this.isAllIndeterminate = false;
      } else if (pNum > 0 || pColorNum > 0) {
        this.checkedAll = false;
        this.isAllIndeterminate = true;
      } else {
        this.checkedAll = false;
        this.isAllIndeterminate = false;
      }
    },
    // 全选
    handleCheckAll() {
      if (this.checkedAll) {
        this.isAllIndeterminate = false;
      }
      this.tableData.forEach(item => {
        item.checked = this.checkedAll;
        if (this.checkedAll) {
          item.isIndeterminate = false;
        }
        item.children.forEach(val => {
          val.checked = item.checked;
          if (val.checked) {
            val.isIndeterminate = false;
          }
          let checkIds = val.functionList.map(item => {
            return item.id;
          });
          val.checkedStatus = item.checked ? checkIds : [];
        });
      });
    },
    changeParentStatus() {
      let pnum = 0;
      let pColorNum = 0;
      this.tableData.forEach(item => {
        if (item.checked) {
          pnum++;
        }
        if (item.isIndeterminate) {
          pColorNum++;
        }
      });
      if (this.tableData.length === pnum) {
        // 子元素都选中
        this.isAllIndeterminate = false;
        this.checkedAll = true;
      } else if (pnum > 0 || pColorNum > 0) {
        // 任意一个子元素选中
        this.isAllIndeterminate = true;
        this.checkedAll = false;
      } else {
        // 子元素都没选中
        this.isAllIndeterminate = false;
        this.checkedAll = false;
      }
    },
    changeModuleStatus(row) {
      let num = 0;
      let color = 0;
      this.tableData[row.pIndex].children.forEach(item => {
        if (item.checked) {
          num++;
        }
        if (item.isIndeterminate) {
          color++;
        }
      });
      // 下级全部选中或者全部未选中
      // 坑 isIndeterminate checked 都为true
      if (this.tableData[row.pIndex].children.length === num) {
        this.tableData[row.pIndex].isIndeterminate = false;
        this.tableData[row.pIndex].checked = true;
      } else if (num > 0 || color > 0) {
        // 任意一个选中 - 标识
        this.tableData[row.pIndex].isIndeterminate = true;
        this.tableData[row.pIndex].checked = false;
      } else {
        this.tableData[row.pIndex].isIndeterminate = false;
        this.tableData[row.pIndex].checked = false;
      }
    },
    // change模块
    handleCheckModule(checked, row) {
      // 全选
      row.checked = checked;
      if (row.children) {
        row.children.forEach(item => {
          item.checked = checked;
          let checkIds = item.functionList.map(val => {
            return val.id;
          });
          if (checked) {
            item.checkedStatus = checkIds;
            item.isIndeterminate = false;
          } else {
            item.checkedStatus = [];
          }
        });
      }
      // 反选
      this.changeParentStatus();
    },
    // change页面
    handleCheckPage(checked, row) {
      // 全选
      let arr = row.functionList.map(item => {
        return item.id;
      });
      if (checked) {
        row.checkedStatus = arr;
        row.isIndeterminate = false;
      } else {
        row.checkedStatus = [];
      }
      // 反选
      this.changeModuleStatus(row);
      this.changeParentStatus();
    },
    // change功能
    handleCheckedFunc(checked, row) {
      // 全选
      row.checked = checked.length === row.functionList.length;
      row.isIndeterminate = checked.length > 0 && checked.length < row.functionList.length;
      // 反选
      this.changeModuleStatus(row);
      this.changeParentStatus();
    },
  },
};
</script>
<style lang="scss" scoped>
$color-white: #fff;
.role-detail-page {
  padding: 12px;
  &-btn {
    background-color: $color-white;
    padding: 12px 16px 12px;
    border-radius: 4px 4px 0px 0px;
  }
  &-form {
    margin: 1px 0 12px;
    padding: 16px 0 0;
    background: $color-white;
  }
  &-extension {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    cursor: pointer;
    padding: 24px 14px 5px;
    background: $color-white;
    color: #595959;
    font-size: 14px;
  }
  &-table {
    background: $color-white;
    ::v-deep .el-table__body .el-table__row td .cell {
      height: auto;
    }
    ::v-deep .el-radio:last-child {
      margin-right: 14px;
    }
    ::v-deep .el-radio {
      margin-right: 5px;
    }
  }
  .role-detail-page-extension {
    i {
      margin-left: 4px;
    }
  }
}
</style>